//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - SaaS Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Shp.Runtime.Sitka.ServiceAgent.Managers;
using Shp.Runtime.Sitka.ServiceAgent;
using Shp.Runtime.Sitka.ServiceAgent.Entities;
using System.Collections.ObjectModel;
using Shp.Runtime.Sitka.ServiceAgent.EntityMappers;
using Shp.Runtime.Sitka.ServiceGateway.SitkaClient;
using System.ServiceModel;
using System.Globalization;
using System.Configuration;

namespace LitwareHR.Portfolio.Deployment
{
    public static class DeploymentServices
    {
         
        private static string LitwareContainerKey = ConfigurationManager.AppSettings["LitwareContainerKey"];

        
        public static void PerformDeploymentProvisioning()
        {
            if (ContainerManager.ContainerExistsForTenant(LitwareContainerKey))
            {
                ContainerManager.DeleteContainer(LitwareContainerKey);
            }

            ContainerManager.CreateContainer(LitwareContainerKey);

            using (Repository<GenericExtensibleEntity> repository = new Repository<GenericExtensibleEntity>(LitwareContainerKey, new GenericExtensibleEntityMapper()))
            {
                //insert default entity
                GenericExtensibleEntity positionEntity = GetPositionEntity();
                repository.Insert(positionEntity);

                //insert default types
                Collection<GenericExtensibleEntity> types = GetDefaultTypes();
                foreach (GenericExtensibleEntity type in types)
                {
                    repository.Insert(type);
                }

                // insert default types
                Collection<GenericExtensibleEntity> views = GetViewDefs();
                foreach (GenericExtensibleEntity view in views)
                {
                    repository.Insert(view);
                }

                // insert actions
                Collection<GenericExtensibleEntity> actions = GetActions();
                foreach (GenericExtensibleEntity action in actions)
                {
                    repository.Insert(action);
                }
            }           
        }

        public static bool ExistsAuthority(string userName, string password, string authorityId)
        {    

            using (SitkaSoapServiceClient client = new SitkaSoapServiceClient())
            {
                client.ClientCredentials.UserName.UserName = userName;
                client.ClientCredentials.UserName.Password = password;

                Scope authorityScope = new Scope();
                authorityScope.AuthorityId = authorityId.Replace("-", "x").ToLower(CultureInfo.InvariantCulture);
                                
                Authority authority = new Authority();
                authority.Id = authorityScope.AuthorityId;

                Entity authorityRetrieved = null;

                try
                {
                    authorityRetrieved = client.Get(authorityScope);
                }
                catch
                {
                    //intentionally
                }

                return authorityRetrieved != null;
            }

        }

        public static void CreateAuthority()
        {
            string authorityId = String.Format(CultureInfo.InvariantCulture, "litware{0}", Guid.NewGuid());
            CreateAuthority("litodamiani", "hb6i#vekx!1367o$rsb3", authorityId);
        }

        public static void CreateAuthority(string userName, string password, string authorityId)
        {
            using (SitkaSoapServiceClient client = new SitkaSoapServiceClient())
            {
                client.ClientCredentials.UserName.UserName = userName;
                client.ClientCredentials.UserName.Password = password;

                Scope serviceScope = new Scope();
                Authority authority = new Authority();
                authority.Id = authorityId.Replace("-", "x").ToLower(CultureInfo.InvariantCulture);

                client.Create(serviceScope, authority);                
            }
        }

        private static GenericExtensibleEntity GetPositionEntity()
        {
            GenericExtensibleEntity entity = new GenericExtensibleEntity("EntityDef", new Guid("750438de-31a2-4d87-b0c6-28563840947c"));
            entity.Fields.Add(new Field("Name", "position"));

            return entity;
        }

        private static GenericExtensibleEntity CreateAction(string actionId, string uri, string description, bool isSystem)
        {
            GenericExtensibleEntity action = new GenericExtensibleEntity("Action", new Guid(actionId));
            action.Fields.Add(new Field("Uri", uri));
            action.Fields.Add(new Field("Description", description));
            action.Fields.Add(new Field("IsSystem", isSystem));

            return action;
        }

        private static Collection<GenericExtensibleEntity> GetActions()
        {
            Collection<GenericExtensibleEntity> actions = new Collection<GenericExtensibleEntity>();
            actions.Add(CreateAction("7A286167-2E68-4784-8D5C-08358048AD0D", @"http://tempuri.org/IDatamodelSC/UpdateViewDef", "Update View Definition", false));
            actions.Add(CreateAction("209D56B7-5FB3-400C-96FB-0913E33D16B3", @"http://tempuri.org/IProcessSC/GetRecruitingWorkflowListByApplicant", "Get Recruiting WorkflowList By Applicant", false));
            actions.Add(CreateAction("0B205A72-92A2-4CEB-B94F-0B20A41B4AE0", @"http://tempuri.org/IProcessSC/GetSilverlightAccount", "Get Silverlight Account", false));
            actions.Add(CreateAction("F4B57E7D-4820-4187-A125-134D2D2432ED", @"http://tempuri.org/IProcessSC/GetOpenPositionEntityList", "Get Open Position Entity List", false));
            actions.Add(CreateAction("7E358B4B-A4E5-492D-8449-179AA0D9913C", @"http://tempuri.org/IPresentationSC/GetMainMenuList", "Get Main Menu List", false));
            actions.Add(CreateAction("EE0325C8-1EB3-4122-B25C-17CB944A8FAC", @"http://tempuri.org/IProcessSC/SubmitResume", "Submit Resume", false));
            actions.Add(CreateAction("CA4B1243-579E-49D2-9963-1B738DD203F1", @"http://tempuri.org/IWorkflowSC/AddWorkflowDef", "Add Workflow Definition", false));
            actions.Add(CreateAction("38648E21-D2BF-45E7-95F6-1F8F5990129E", @"http://tempuri.org/IProcessSC/GetResume", "Get Resume", false));
            actions.Add(CreateAction("C0CB972E-870D-40EE-9796-2B0D4E8E6272", @"http://tempuri.org/IPresentationSC/AddStyle", "Add Style", false));
            actions.Add(CreateAction("C1BE9554-117B-4904-9C0E-2C6D566763A8", @"http://tempuri.org/IDatamodelSC/UpdateEntityDef", "Update Entity Definition", false));
            actions.Add(CreateAction("FE55B9C1-B009-4706-9E45-328D542CF1CB", @"http://tempuri.org/IPresentationSC/UpdatePresentation", "Update Presentation", false));
            actions.Add(CreateAction("1C3F429B-FE40-4823-8451-37AA75CC3245", @"http://tempuri.org/IWorkflowSC/UpdateWorkflowDef", "Update Workflow Definition", false));
            actions.Add(CreateAction("53B60DB8-37D8-48B0-B84E-3AD20C42F280", @"http://tempuri.org/IProcessSC/SubmitInterview", "Submit Interview", false));
            actions.Add(CreateAction("017837EE-B9D1-4F62-8E25-3CA2DDFDD083", @"http://tempuri.org/IAuthorizationSC/UpdateCredentialPermission", "Update Credential Permission", false));
            actions.Add(CreateAction("F496D0EE-9F53-4779-9C1C-41C0C6AE3BB9", @"http://tempuri.org/IProcessSC/SubmitAcceptance", "Submit Acceptance", false));
            actions.Add(CreateAction("DFB66486-752A-417C-ACAD-472845E6D237", @"http://tempuri.org/IWorkflowSC/GetWorkflowDefList", "Get Workflow Def List", false));
            actions.Add(CreateAction("48A549D2-5659-48A1-8937-49E3D8D9CC03", @"http://tempuri.org/IPresentationSC/GetCurrentStyleId", "Gets the currently selected style id", false));
            actions.Add(CreateAction("64DEB709-01B2-4F15-AF9E-80029F3F29DA", @"http://tempuri.org/IAuthorizationSC/GetCredentialPermissionList", "Get Credential Permission List", false));
            actions.Add(CreateAction("E77B2C50-4F1D-4155-9711-836DEE00C1CC", @"http://tempuri.org/IProcessSC/GetRecruitingWorkflowList", "Get Recruiting Workflow List", false));
            actions.Add(CreateAction("72740A4A-9BCC-43BC-AA1E-8FA6D6369A5A", @"http://tempuri.org/IAuthenticationSC/RemoveUserFromRole", "Remove User From Role", false));
            actions.Add(CreateAction("EB551C70-9D61-4CA3-A2A3-9122CC353EEA", @"http://tempuri.org/IProcessSC/AddVideoResume", "Add Video Resume", false));
            actions.Add(CreateAction("DEAB2B87-0026-48A9-AC42-9CF2B91700C3", @"http://tempuri.org/IAuthenticationSC/DeleteRole", "Deletes a Role", false));
            actions.Add(CreateAction("D8DDE34D-D04C-456E-A85C-9D2B90352FC6", @"http://tempuri.org/IPresentationSC/GetStyleList", "Get Style List", false));
            actions.Add(CreateAction("90F718F0-A6DF-45C9-BC30-9DABC9DA9B61", @"http://tempuri.org/ISystemSC/Ping", "Ping", true));
            actions.Add(CreateAction("70AFEFB5-7819-40B8-B9F1-A66E314AF51E", @"http://tempuri.org/IWorkflowSC/GetRuleSetDef", "Get RuleSet Def", false));
            actions.Add(CreateAction("8EC012F1-55ED-4693-9964-A70B5F4AF6E9", @"http://tempuri.org/IWorkflowSC/UpdateRuleSetDef", "Update RuleSet Def", false));
            actions.Add(CreateAction("ADE8ED9B-982E-4976-B94E-A957B1781E0D", @"http://tempuri.org/IAuthenticationSC/CreateRole", "Create a new Role", false));
            actions.Add(CreateAction("151251D4-0EF3-4C4D-8961-B93C93136CC2", @"http://tempuri.org/IProcessSC/SubmitNegotiation", "Submit Negotiation", false));
            actions.Add(CreateAction("AD5457AB-C0C9-47F0-926E-BFDDC91035DE", @"http://tempuri.org/IPresentationSC/GetLayoutList", "Get Layout List", false));
            actions.Add(CreateAction("141BA49B-4422-4A95-BBCD-D57DF8F4032B", @"http://tempuri.org/IWorkflowSC/GetWorkflowDef", "Get Workflow Def", false));
            actions.Add(CreateAction("CF4FCF27-062F-4DCA-A344-DD73E5116097", @"http://tempuri.org/IProcessSC/SubmitRejection", "Submit Rejection", false));
            actions.Add(CreateAction("33DF083F-0210-4444-A570-E26ECC5308F4", @"http://tempuri.org/IDatamodelSC/AddInstance", "Add Instance", false));
            actions.Add(CreateAction("DFAF1895-4766-4D38-BB30-E45C6A9A10E6", @"http://tempuri.org/IProcessSC/OpenRecruitingProcess", "Open Recruiting Process", false));
            actions.Add(CreateAction("2E96F8B1-40BD-4BFD-9593-E4F6EFCA627C", @"http://tempuri.org/IPresentationSC/UpdateMainMenu", "Update Main Menu", false));
            actions.Add(CreateAction("CCACD890-3E6C-4430-AAF8-EFDDE5EA1A8B", @"http://tempuri.org/IAuthenticationSC/AddUserToRole", "Add User To Role", false));
            actions.Add(CreateAction("451110CF-BF04-4B0C-9B72-6516A8059299", @"http://tempuri.org/IProcessSC/SearchResumes", "Search Resumes", false));
            actions.Add(CreateAction("E1AECD4B-E951-4690-AF38-5D3BEA445102", @"http://tempuri.org/IProcessSC/SearchCrossTenantResumes", "Search Multi-Tenant Resumes", false));

            return actions;
        }

        private static Collection<GenericExtensibleEntity> GetDefaultTypes()
        {
            Collection<GenericExtensibleEntity> types = new Collection<GenericExtensibleEntity>();

            GenericExtensibleEntity type = new GenericExtensibleEntity("Type", new Guid("a82c6a4f-0389-4882-bd23-1ccf13a3c63e"));
            type.Fields.Add(new Field("Name", "Boolean (Yes | No)"));
            types.Add(type);

            type = new GenericExtensibleEntity("Type", new Guid("b44a04ca-3426-4c8d-9fc0-431de22d6f4e"));
            type.Fields.Add(new Field("Name", "Long text (up to 4000 characters)"));
            types.Add(type);

            type = new GenericExtensibleEntity("Type", new Guid("fa564e7c-f59b-480f-a768-a1d02a34e32c"));
            type.Fields.Add(new Field("Name", "Short text (up to 255 characters)"));
            types.Add(type);

            type = new GenericExtensibleEntity("Type", new Guid("8863152f-f10e-4f7d-819f-b4bf05eb8b24"));
            type.Fields.Add(new Field("Name", "Number"));
            types.Add(type);

            type = new GenericExtensibleEntity("Type", new Guid("018d42ba-ca23-4e15-9c01-e941c86dd36f"));
            type.Fields.Add(new Field("Name", "Date and time"));
            types.Add(type);

            return types;

        }

        private static Collection<GenericExtensibleEntity> GetViewDefs()
        {
            Collection<GenericExtensibleEntity> views = new Collection<GenericExtensibleEntity>();

            GenericExtensibleEntity view = new GenericExtensibleEntity("ViewDef", new Guid("0c7063d6-fcd7-4341-9732-3361d89da33b"));
            view.Fields.Add(new Field("Name", "jobDetail"));
            view.Fields.Add(new Field("EntityDefId", "750438de-31a2-4d87-b0c6-28563840947c"));
            views.Add(view);

            view = new GenericExtensibleEntity("ViewDef", new Guid("4453d801-2027-4e87-aebc-52aaaf507269"));
            view.Fields.Add(new Field("Name", "jobSearch"));
            view.Fields.Add(new Field("EntityDefId", "750438de-31a2-4d87-b0c6-28563840947c"));
            views.Add(view);            

            return views;
        }
    }    
}
